package com.css.dzj.dzjjcss.modules.publicity.service.impl;

import com.css.dzj.dzjjcss.common.util.Constant;
import com.css.dzj.dzjjcss.common.util.ServiceUtil;
import com.css.dzj.dzjjcss.common.util.SnowflakeId;
import com.css.dzj.dzjjcss.modules.publicity.entity.PublicityEntity;
import com.css.dzj.dzjjcss.modules.publicity.entity.QPublicityEntity;
import com.css.dzj.dzjjcss.modules.publicity.mapper.PublicityMapper;
import com.css.dzj.dzjjcss.modules.publicity.service.PublicityService;
import com.css.dzj.dzjjcss.modules.todo.entity.JcssTodoEntity;
import com.css.dzj.dzjjcss.modules.todo.service.TodoService;
import com.querydsl.core.QueryResults;
import com.querydsl.core.types.ExpressionUtils;
import com.querydsl.core.types.Predicate;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 公式通报实现层
 * @author wt
 * @date 2020\3\24 0024
 */
@Service
public class PublicityServiceImpl implements PublicityService {

    @Autowired
    private PublicityMapper pMapper;

    @Autowired
    private JPAQueryFactory jpaQueryFactory;

    @Autowired
    private HttpServletRequest request;

    //代办接口
    @Autowired
    private TodoService todoService;


    /**
     * 暂存公示通报信息
     */
    @Override
    @Transactional
    public void add(PublicityEntity pEntity) {

        try{
            pEntity.setCreateUser(ServiceUtil.getLoginName(request));
            pEntity.setCreateUserUnit(ServiceUtil.getOrgName(request));
            //pEntity.setId(SnowflakeId.getId());
            pEntity.setDelFlag(Constant.NO_DELETE);
            pEntity.setCreateTime(new Date());
            pEntity.setPxTime(new Date());
            pEntity.setStatus("0");
            pEntity.setOtherMsg("0");//暂存标识
            pMapper.save(pEntity);

        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 发布在新建的时候公示通报信息
     */
    @Override
    @Transactional
    public void saverelease(PublicityEntity pEntity) {

        try{
            pEntity.setCreateUser(ServiceUtil.getLoginName(request));
            pEntity.setCreateUserUnit(ServiceUtil.getOrgName(request));
            //pEntity.setId(SnowflakeId.getId());
            pEntity.setDelFlag(Constant.NO_DELETE);
            pEntity.setCreateTime(new Date());
            pEntity.setPxTime(new Date());
            pEntity.setStatus("1");
            pEntity.setOtherMsg("1");//保存发布标识
            pMapper.save(pEntity);

            //调取代办接口
            JcssTodoEntity jsTodoEntity = new JcssTodoEntity();
            jsTodoEntity.setStatus("1");//代表代办
            jsTodoEntity.setCreateTime(new Date());
            jsTodoEntity.setDelFlag(Constant.NO_DELETE);
            jsTodoEntity.setTitle(pEntity.getTitle());
            jsTodoEntity.setLinkId(pEntity.getId());
            //查看详情页
            jsTodoEntity.setUrl("../todolist/publick.html");
            jsTodoEntity.setLocation(ServiceUtil.getOrgName(request));
            jsTodoEntity.setCreatePerson(ServiceUtil.getLoginName(request));
            todoService.add(jsTodoEntity);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 修改公示通报信息
     */
    @Override
    @Transactional
    public void update(PublicityEntity pEntity) {

    }

    /**
     * 通过id查询公示通报信息
     */
    @Override
    public PublicityEntity findById(String id) {
        if(StringUtils.isEmpty(id)){
            throw new RuntimeException("传递参数为空");
        }
        QPublicityEntity qEntity =  QPublicityEntity.publicityEntity;
        return jpaQueryFactory
                .selectFrom(qEntity)
                .where(qEntity.id.eq(id),
                        qEntity.delFlag.eq(Constant.NO_DELETE)
                        )
                .fetchOne();
    }

    /**
     * 分页查询公示通报信息
     */
    @Override
    public QueryResults<PublicityEntity> queryPage(Pageable pageable) {

        QPublicityEntity qEntity =  QPublicityEntity.publicityEntity;
        Predicate predicate = qEntity.isNotNull().or(qEntity.isNull());
        predicate = ExpressionUtils.and(predicate, qEntity.delFlag.eq(Constant.NO_DELETE)) ;
        QueryResults<PublicityEntity> publicResults = jpaQueryFactory.selectFrom(qEntity)
                .where(predicate)
                .orderBy(qEntity.pxTime.desc())
                .offset(pageable.getOffset())
                .limit(pageable.getPageSize())
                .fetchResults();
        return publicResults;
    }

    /**
     * 删除公示通报信息
     */
    @Override
    @Transactional
    public Boolean delete(String id) {

        if(StringUtils.isEmpty(id)){
            throw new RuntimeException("传递参数为空");
        }
        try{
            QPublicityEntity qEntity =  QPublicityEntity.publicityEntity;
            jpaQueryFactory
                    .update(qEntity)
                    .set(qEntity.delFlag,Constant.DELETE)
                    .where(
                            qEntity.id.eq(id),
                            qEntity.delFlag.eq(Constant.NO_DELETE)
                    )
                    .execute();
            return true;
        }catch (Exception e){
            return false;
        }
    }

    /**
     * 多条件分页查询公示通报信息
     */
    @Override
    public QueryResults<PublicityEntity> getGstbList(String createUser, String title, String createUserUnit, String status, String releaseStartTime, String releaseEndTime, Pageable pageable) {

        QPublicityEntity q =  QPublicityEntity.publicityEntity;

        Predicate predicate = q.isNotNull().or(q.isNull());
        predicate = ("".equals(createUser) || createUser == null) ? predicate : ExpressionUtils.and(predicate, q.createUser.like("%"+createUser+"%"));
        predicate = ("".equals(title) || title == null) ? predicate : ExpressionUtils.and(predicate, q.title.like("%"+title+"%"));
        predicate = ("".equals(createUserUnit) || createUserUnit == null) ? predicate : ExpressionUtils.and(predicate, q.createUserUnit.like("%"+createUserUnit+"%"));
        predicate = ("".equals(status) || status == null) ? predicate : ExpressionUtils.and(predicate, q.status.eq(status));

        /* 只有结束时间*/
        if ((StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                endDate = sf.parse(releaseEndTime+ " " + "23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.createTime.loe(endDate));
        }
/** 只有开始时间 **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                startDate = sf.parse(releaseStartTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.createTime.goe(startDate));
        }
/** 时间都不为空 **/
        if ((!StringUtils.isEmpty(releaseStartTime)) && (!StringUtils.isEmpty(releaseEndTime))) {
            Date startDate = null;
            Date endDate = null;
            SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd");
            SimpleDateFormat sfd = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
            try {
                startDate = sf.parse(releaseStartTime);
                endDate = sfd.parse(releaseEndTime+ " " + "23:59:59.999");
            } catch (ParseException e) {
                e.printStackTrace();
            }
            predicate = ExpressionUtils.and(predicate, q.createTime.between(startDate, endDate));
        }

        predicate = ExpressionUtils.and(predicate, q.delFlag.eq(Constant.NO_DELETE)) ;

        return  jpaQueryFactory
                .selectFrom(q)
                .where(
                        predicate
                )
                .orderBy(q.createTime.desc())
                .offset(pageable.getOffset())   //起始页
                .limit(pageable.getPageSize())  //每页大小
                .fetchResults();
    }

    /**
     * 向外提供接口
     * 多条件分页查询公示通报
     * @author wt
     * @date 2020\3\24 0024
     */
    @Override
    public List termList(String title, String publicType, String isPublic) {

        QPublicityEntity qEntity = QPublicityEntity.publicityEntity;
        Predicate predicate = qEntity.isNotNull().or(qEntity.isNull());
        predicate = (title == null || title.isEmpty()) ? predicate : ExpressionUtils.and(predicate, qEntity.title.like("%" + title + "%"));
        if(publicType.equals("0")){
            predicate = ExpressionUtils.and(predicate, qEntity.publicType.ne("1"));
        }else{
            predicate = ExpressionUtils.and(predicate, qEntity.publicType.ne("0"));
        }
        predicate = ExpressionUtils.and(predicate, qEntity.delFlag.eq(Constant.NO_DELETE));
        predicate = ExpressionUtils.and(predicate, qEntity.status.eq("1")) ;
        predicate = ExpressionUtils.and(predicate, qEntity.isPublic.eq(isPublic));
        List<PublicityEntity> list = jpaQueryFactory.selectFrom(qEntity)
                .where(predicate)
                .orderBy(qEntity.releaseTime.desc())
                .fetch();
        return list;
    }

    /**
     * 向外提供接口
     * 分页查询公示通报
     * @author wt
     * @date 2020\3\24 0024
     */
    @Override
    public List pageList(String publicType, String isPublic) {
        QPublicityEntity qEntity = QPublicityEntity.publicityEntity;
        Predicate predicate = qEntity.isNotNull().or(qEntity.isNull());
        if(publicType.equals("0")){
            predicate = ExpressionUtils.and(predicate, qEntity.publicType.ne("1"));
        }else{
            predicate = ExpressionUtils.and(predicate, qEntity.publicType.ne("0"));
        }
        predicate = ExpressionUtils.and(predicate, qEntity.delFlag.eq(Constant.NO_DELETE)) ;
        predicate = ExpressionUtils.and(predicate, qEntity.status.eq("1"));
        predicate = ExpressionUtils.and(predicate, qEntity.isPublic.eq(isPublic));
        List<PublicityEntity> list = jpaQueryFactory.selectFrom(qEntity)
                .where(predicate)
                .orderBy(qEntity.releaseTime.desc())
                .fetch();
        return list;
    }
}

